Java - tutorial - 13/13 - user input

revision:


Java - User input

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation:

method:nextBoolean(); description: reads a boolean value from the user.

method:nextByte(); description: reads a byte value from the user.

method:nextDouble(); description: reads a double value from the user.

method:nextFloat(); description: reads a float value from the user.

method:nextInt(); description: reads a int value from the user.

method:nextLine(); description: reads a String value from the user.

method:nextLong(); description: reads a long value from the user.

method:nextShort(); description: reads a short value from the user.

example

        import java.util.Scanner;

        class Main {
          public static void main(String[] args) {
            Scanner myObj = new Scanner(System.in);
        
            System.out.println("Enter name, age and salary:");
        
            // String input
            String name = myObj.nextLine();
        
            // Numerical input
            int age = myObj.nextInt();
            double salary = myObj.nextDouble();
        
            // Output input by user
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Salary: " + salary);
          }
        }
    

Java - Date and Time

Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes:

class:LocalDate; description: represents a date (year, month, day (yyyy-MM-dd)).

class:LocalTime; description: represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns)).

class:LocalDateTime; description: represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns).

class:DateTimeFormatter; description: formatter for displaying and parsing date-time objects.

To display the current date, import the java.time.LocalDate class, and use its now() method.

To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method.

example

    import java.time.LocalTime; // import the LocalTime class

    public class Main {
      public static void main(String[] args) {
        LocalTime myObj = LocalTime.now();
        System.out.println(myObj);
      }
    }
    

Java - Arraylist

The ArrayList class is a resizable array, which can be found in the "java.util" package.

The difference between a built-in array and an ArrayList in Java:

the size of an array cannot be modified. If you want to add or remove elements to/from an array, you have to create a new one.
elements can be added and removed from an ArrayList whenever you want.
the syntax is also slightly different.

The ArrayList class has many useful methods. For example, to add elements to the ArrayList, use the add() method.

To access an element in the ArrayList, use the get() method and refer to the index number.

To modify an element, use the set() method and refer to the index number.

To remove an element, use the remove() method and refer to the index number.

To remove all the elements in the ArrayList, use the clear() method.

To find out how many elements an ArrayList have, use the size() method.

Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run. You can also loop through an ArrayList with the for-each loop.

example

        public class Main {
            public static void main(String[] args) {
              ArrayList cars = new ArrayList();
              cars.add("Volvo");
              cars.add("BMW");
              cars.add("Ford");
              cars.add("Mazda");
              for (String i : cars) {
                System.out.println(i);
              }
            }
        }
    

Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically.

example

        import java.util.ArrayList;
        import java.util.Collections;  // Import the Collections class

        public class Main {
            public static void main(String[] args) {
                ArrayList myNumbers = new ArrayList();
                myNumbers.add(33);
                myNumbers.add(15);
                myNumbers.add(20);
                myNumbers.add(34);
                myNumbers.add(8);
                myNumbers.add(12);

                Collections.sort(myNumbers);  // Sort myNumbers

                for (int i : myNumbers) {
                System.out.println(i);
                }
            }
        }
    

Java - LinkedList

The LinkedList class is almost identical to the ArrayList.

The LinkedList class is a collection which can contain many objects of the same type, just like the ArrayList.
The LinkedList class has all of the same methods as the ArrayList class, because they both implement the List interface. This means that you can add items, change items, remove items and clear the list in the same way.
However, while the ArrayList class and the LinkedList class can be used in the same way, they are built very differently.

The ArrayList class has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed.
The LinkedList stores its items in "containers". The list has a link to the first container and each container has a link to the next container in the list. To add an element to the list, the element is placed into a new container and that container is linked to one of the other containers in the list.

For many cases, the ArrayList is more efficient as it is common to need access to random items in the list, but the LinkedList provides several methods to do certain operations more efficiently.

method:addFirst(); description: adds an item to the beginning of the list.

method:addLast(); description: add an item to the end of the list.

method:removeFirst(); description: remove an item from the beginning of the list.

method:removeLast(); description: remove an item from the end of the list.

method:getFirst(); description: get the item at the beginning of the list.

method:getLast(); description: get the item at the end of the list.

example

        // Import the LinkedList class
        import java.util.LinkedList;

        public class Main {
            public static void main(String[] args) {
                LinkedList cars = new LinkedList();
                cars.add("Volvo");
                cars.add("BMW");
                cars.add("Ford");
                cars.add("Mazda");
                System.out.println(cars);
            }
        }
    

Java - HashMap

A HashMap stores items in "key/value" pairs, and you can access them by an index of another type (e.g. a String).

One object is used as a key (index) to another object (value).
It can store different types: String keys and Integer values, or the same type, like: String keys and String values.

example

 create a HashMap object called capitalCities that will store String keys and String values:
        import java.util.HashMap; // import the HashMap class

        HashMap<String, String> capitalCities = new HashMap<String, String>();
    

The HashMap class has many useful methods:

to add items to it, use the put() method.

to access a value in the HashMap, use the get() method and refer to its key.

to remove an item, use the remove() method and refer to the key.

to remove all items, use the clear() method.

to find out how many items there are, use the size() method.

Loop through the items of a HashMap with a for-each loop. Use the keySet() method if you only want the keys, and use the values() method if you only want the values.


Java - HashSet

A HashSet is a collection of items where every item is unique, and it is found in the java.util package.

The HashSet class has many useful methods:

to add items to it, use the add() method.

to check whether an item exists in a HashSet, use the contains() method:.

to remove an item, use the remove() method.

to remove all items, use the clear() method.

to find out how many items there are, use the size() method.

Loop through the items of a HashSet with a for-each loop.


Java - Iterator

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical term for looping.

To use an Iterator, you must import it from the java.util package.

the iterator() method can be used to get an Iterator for any collection.

to loop through a collection, use the hasNext() and next() methods of the Iterator.

Iterators are designed to easily change the collections that they loop through. The remove() method can remove items from a collection while looping.

example

        import java.util.ArrayList;
        import java.util.Iterator;

        public class Main {
            public static void main(String[] args) {
                ArrayList numbers = new ArrayList();
                numbers.add(12);
                numbers.add(8);
                numbers.add(2);
                numbers.add(23);
                Iterator it = numbers.iterator();
                while(it.hasNext()) {
                    Integer i = it.next();
                    if(i < 10) {
                        it.remove();
                    }
                }
                System.out.println(numbers);
            }
        }
    

Note: Trying to remove items using a for loop or a for-each loop would not work correctly because the collection is changing size at the same time that the code is trying to loop.


Java - Wrapper Classes

Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.The primitive type and the equivalent wrapper class are as follows:

primitive data type: byte; wrapper class: Byte.

primitive data type: short; wrapper class: Short.

primitive data type: int; wrapper class: Integer.

primitive data type: long; wrapper class: Long.

primitive data type: float; wrapper class: Float.

primitive data type: double; wrapper class: Double.

primitive data type: boolean; wrapper class: Boolean.

primitive data type: char; wrapper class: Character.

Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList, where primitive types cannot be used (the list can only store objects).

To create a wrapper object, use the wrapper class instead of the primitive type. To get the value, you can just print the object.

Since you're now working with objects, you can use certain methods to get information about the specific object.

For example, the following methods are used to get the value associated with the corresponding wrapper object: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), booleanValue().
Another useful method is the toString() method, which is used to convert wrapper objects to strings.


Java - Exceptions

When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.

When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).

Java try and catch: the "try" statement allows you to define a block of code to be tested for errors while it is being executed. The "catch" statement allows you to define a block of code to be executed, if an error occurs in the try block.The try and catch keywords come in pairs:

example

        try {
            //  Block of code to try
          }
          catch(Exception e) {
            //  Block of code to handle errors
          }
    

If an error occurs, we can use "try...catch" to catch the error and execute some code to handle it.

The finally statement lets you execute code, after try...catch, regardless of the result.

example

        public class Main {
            public static void main(String[] args) {
                try {
                    int[] myNumbers = {1, 2, 3};
                    System.out.println(myNumbers[10]);
                } catch (Exception e) {
                    System.out.println("Something went wrong.");
                } finally {
                    System.out.println("The 'try catch' is finished.");
                }
            }
        }
    

The throw statement allows you to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:

example

        public class Main {
            static void checkAge(int age) {
              if (age < 18) {
                throw new ArithmeticException("Access denied - You must be at least 18 years old.");
              }
              else {
                System.out.println("Access granted - You are old enough!");
              }
            }
          
            public static void main(String[] args) {
              checkAge(15); // Set age to 15 (which is below 18...)
            }
          }
    

Java - Regular Expressions (RegEx)

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.

Java does not have a built-in Regular Expression class, but we can import the java.util.regex package to work with regular expressions. The package includes the following classes:

Pattern Class - defines a pattern (to be used in a search)
Matcher Class - used to search for the pattern
PatternSyntaxException Class - indicates syntax error in a regular expression pattern


Java - Threads

Threads allows a program to operate more efficiently by doing multiple things at the same time. Threads can be used to perform complicated tasks in the background without interrupting the main program.

There are two ways to create a thread.

It can be created by extending the Thread class and overriding its run() method.

Extend syntax:
        public class Main extends Thread {
            public void run() {
              System.out.println("This code is running in a thread");
            }
          }
    

Another way to create a thread is to implement the Runnable interface

Implement syntax:
        public class Main implements Runnable {
            public void run() {
              System.out.println("This code is running in a thread");
            }
          }
    

If the class extends the Thread class, the thread can be run by creating an instance of the class and call its start() method:

If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method:

Ther major difference between "extending" and "implementing" Threads is that when a class extends the Thread class, you cannot extend any other class, but by implementing the Runnable interface, it is possible to extend from another class as well, like: class MyClass extends OtherClass implements Runnable.

Because threads run at the same time as other parts of the program, there is no way to know in which order the code will run.

When the threads and main program are reading and writing the same variables, the values are unpredictable. The problems that result from this are called concurrency problems.

To avoid concurrency problems, it is best to share as few attributes between threads as possible. If attributes need to be shared, one possible solution is to use the isAlive() method of the thread to check whether the thread has finished running before using any attributes that the thread can change.


Java - Lambda Expressions

Lambda Expressions were added in Java 8.

A lambda expression is a short block of code which takes in parameters and returns a value.

Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

Syntax: the simplest lambda expression contains a single parameter and an expression:

 parameter -> expression

Syntax: to use more than one parameter, wrap them in parentheses:

(parameter1, parameter2) -> { code block }

Lambda expressions are usually passed as parameters to a function.

Lambda expressions can be stored in variables if the variable's type is an interface, which has only one method. The lambda expression should have the same number of parameters and the same return type as that method. Java has many of these kinds of interfaces built in, such as the Consumer interface (found in the java.util package) used by lists.

To use a lambda expression in a method, the method should have a parameter with a single-method interface as its type. Calling the interface's method will run the lambda expression.